package com.e_manager.soft.emanager.service.impl;

import com.e_manager.soft.emanager.entity.User;
import com.e_manager.soft.emanager.service.TokenManager;
import com.e_manager.soft.emanager.service.UserService;
import com.e_manager.soft.emanager.token.TokenConstant;
import com.e_manager.soft.emanager.token.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author : lip[lip4051@163.com]
 * @create : 2018/3/14 0014 上午 9:04
 */
@Service
public class TokenManagerImpl implements TokenManager {
    @Autowired
    private UserService userSerice;

    @Override
    public TokenModel createToken(long userId) {
        return null;
    }

    /**
     * 创建一个token关联上指定用户
     *
     * @param user 指定用户
     * @return 生成的token
     * @see com.e_manager.soft.emanager.token.TokenModel
     * @see com.e_manager.soft.emanager.entity.User
     */
    @Override
    public TokenModel createToken(User user) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        user.setToken(token);
        user.setTokenTime(LocalDateTime.now().plusHours(TokenConstant.TOKEN_EXPIRES_HOUR));
//        LocalDateTimeUtil  localDateTimeUtil= LocalDateTimeUtil.getInstance();
//        user.setTokenTime(localDateTimeUtil.LocaldateTimeToDate(localDateTimeUtil.plus(Constants.TOKEN_EXPIRES_HOUR, ChronoUnit.HOURS)));
        userSerice.updateUser(user);
        TokenModel model = new TokenModel(user.getUserID(), token);
        return model;
    }

    @Override
    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        User user = userSerice.getByUserId(model.getUserId());
        if (user == null || !user.getToken().equals(model.getToken())) {
            return false;
        }
        //判断token存在时间是否有效
        LocalDateTime tokenDatetime = user.getTokenTime();
        if (tokenDatetime == null) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        boolean isExpired = LocalDateTime.now().isBefore(tokenDatetime);
        if (isExpired) {
            user.setToken(model.getToken());
            user.setTokenTime(LocalDateTime.now().plusHours(TokenConstant.TOKEN_EXPIRES_HOUR));
            userSerice.updateUser(user);
        } else {
            return false;
        }

        return isExpired;
    }

    @Override
    public TokenModel getToken(String authentication) {

        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        String userId = "";
        try {
            userId = String.valueOf(param[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String token = param[1];
        return new TokenModel(userId, token);
    }

    @Override
    public void deleteToken(long userId) {

    }
}
